mongodb = require('mongodb')
ObjectId = mongodb.ObjectId
MongoClient = mongodb.MongoClient

log = require('./log')
config = require("./config")

mongoChain = require('./mongoChain')


databases = {}

gDb = (tag, url)->
    db = databases[tag]
    return db if db?

    db = yield MongoClient.connect url

    databases[tag] = db

    db.on 'close', ->
        log.system.info 'Mongo DB closed'
        delete databases[tag]
    db.on 'error', (e)->
        log.system.error e, 'Mongo DB error'
        delete databases[tag]
    db.on 'reconnect', ->
        log.system.info 'Mongo DB reconnect'

    db

exports.gDatabase = -> yield from gDb 'forum', config.mongoUrl

exports.gDispose = ->
    for tag, db of databases
        try
            yield db.close()
        catch e
            log.system.error e, 'gDispose'

exports.find = (query, col, params)->
    mongoChain(query, col, params)

# 返回值是ObjectId
exports.getInsertedIdObject = (insertResponse)->
    return insertResponse?.insertedId || null

exports.isIndexConflictError = (e)-> e.code == 11000

exports.stringToObjectId = (string)->
    return null unless string
    if string instanceof ObjectId
        string
    else
        new ObjectId string

exports.stringToObjectIdSilently = (string)->
    return null unless string
    if string instanceof ObjectId
        string
    else
        try
            new ObjectId string
        catch
            null

exports.stringArrayToObjectIdArraySilently = (strings)->
    return [] unless strings?
    ids = []
    for s in strings
        id = exports.stringToObjectIdSilently s
        ids.push id if id?
    return ids
